<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Warehouse\Controllers;

use App\Eloquent\Ygt\BuyersAddress;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseBill;
use App\Eloquent\Ygt\WarehouseBillRelation;
use App\Eloquent\Ygt\WarehouseOut;
use App\Eloquent\Ygt\WarehouseOutRelation;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class OutController extends Controller
{
    public $userId          = 25;

    //应收单准备生成出库的列表
    public function bill()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $dealStatus         = request('deal_status',0);
        $keyword        = request('keyword','');
        $customerId        = request('customer_id','');

        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = [ 'company_id'=>$companyId];
//        $where['deal_status']   = $dealStatus;

        //过滤客户
        //2019-01-23 Linwei  交货单列表增加只显示本厂的限制
        if($customerId){
            $where = [ 'customer_id'=>$customerId,'company_id'=>$companyId];
        }else{
            //不筛选客户&不是显示已出库，暂定为仓库选择出库单
            if(!$dealStatus){
                $where = [ 'status'=> 1,'company_id'=>$companyId];
            }
        }

        $limit              = $offset = '';
        $billColltion       = WarehouseBill::getList($where);
        $billList           = $billColltion->toArray();
        $warehouseBillIdArr = $billColltion->pluck('id');
        $where              = ['warehouse_bill_id'=>['in',$warehouseBillIdArr]];

        if(!empty($keyword)){
            $warehouseIdArr = Warehouse::where('product_name','like',"%".$keyword."%")->get()->pluck('id');
            $where['warehouse_id'] = ['in',$warehouseIdArr];
        }

        $relationColletion  = WarehouseBillRelation::getList($where);
        $billRelationList   = $this->changeBillRelationColletion($relationColletion,$dealStatus,1);
        foreach($billList as $key=>$val)
        {
            $valId          = $val['id'];
            $valUpdate      = $val['updated_at'];
            $valUpdateYmd   = '';
            if($valUpdate)
            {
                $valUpdateYmd   = date('Y-m-d',$valUpdate);
            }
            if(isset($billRelationList[$valId]))
            {
                $tempData   = $billRelationList[$valId];

                //处理发货时间
                $sendTime = '';
                if($val['send_time']){
                    $sendTime = date('Y-m-d',$val['send_time']);
                }

                foreach($tempData as $k=>$v)
                {
                    $tempData[$k]['deal_date']  = $valUpdateYmd;
                    $tempData[$k]['send_time']  = $sendTime;
                }
                $size       = count($tempData);
                $billList[$key]['sn']   = $val['sn'];

                //现在单号上加状态 20181230 zhuyujun
                if($val['status']){
                    $tmpStatusList  = config('status.warehouse_bill_status');
                    if(isset($tmpStatusList[$val['status']])){
                        $billList[$key]['sn'].= "【{$tmpStatusList[$val['status']]['txt']}】";
                    }

                }

                //处理件数，未出库不显示件数，已出库的数据进行处理
                foreach ($tempData as $tmpKey => $tmpRow){
//                    if($tmpRow['packages']<=0){
//                        continue;
//                    }

                    if($dealStatus){//已出库
                        $tempData[$tmpKey]['packages'] = "共{$tmpRow['packages']}件";
                    }else{//未出库
                        $tempData[$tmpKey]['packages'] = "";
                    }

                    $tempData[$tmpKey]['bill_number'] = "×{$tmpRow['bill_number']}";

                    //件数先不显示
                    $tempData[$tmpKey]['packages'] = '';


                }


                $billList[$key]['size'] = $size;
                $billList[$key]['data'] = $tempData;
            }
        }
        $result         = [
            'bill_list'=>$billList,
            'out_list'=>[],
        ];
        return $result;
    }
    //生成出库单,预览界面,此时不入库
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $billRelationIdStr  = request('bill_relation_id','');
        if( !$userInfo || !$billRelationIdStr || $billRelationIdStr==',')
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        //只有下单人才会显示总计金额
//        $privilegeId        = $userInfo->privilege_id;
//        $isManager          = \App\Eloquent\Ygt\Privilege::getAppnodeId($privilegeId, 1);//是否为下单人（管理员权限）
//        $isShowTotalMoney   = 0;
//        if($isManager)
//        {
//            $isShowTotalMoney   = 1;
//        }
        $isShowTotalMoney   = 0;//不管什么角色都不要看到金额,2018-8-30,周经理提的需求

        $billRelationIdArr  = explode(',',$billRelationIdStr);
        $where              = ['id'=>['in',$billRelationIdArr]];
        $relationColletion  = WarehouseBillRelation::getList($where);
        $billIdArr          = $relationColletion->pluck('warehouse_bill_id');
        $billRelationList   = $this->changeBillRelationColletion($relationColletion);
        $where              = ['id'=>['in',$billIdArr]];
        $billColltion       = WarehouseBill::getList($where);
        $billList           = $billColltion->toArray();
        $totalMoney         = 0.00;
        foreach($billList as $key=>$val)
        {
            $valId          = $val['id'];
            if(isset($billRelationList[$valId]))
            {
                $tempData   = $billRelationList[$valId];
                $size       = count($tempData);
                $billList[$key]['sn']   = $val['sn'];
                $billList[$key]['size'] = $size;
                $billList[$key]['data'] = $tempData;
                foreach($tempData as $k=>$v)
                {
                    $totalMoney += $v['bill_money'];
                }
            }
        }
        $totalMoney     = number_format($totalMoney, 2, '.', '');
        $result         = [
            'bill_list'=>$billList,
            'total_money'=>$totalMoney,
            'is_show_total_money'=>$isShowTotalMoney,
        ];
        return $result;
    }
    //生成出库单,入库
    public function confirm()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $relationJson       = request('relation_arr','');
        $requestRelationArr = [];
        if($relationJson)
        {
            $requestRelationArr = json_decode(htmlspecialchars_decode($relationJson), true);
        }
        if( !$userInfo || empty($requestRelationArr) )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $nowTime            = $_SERVER['REQUEST_TIME'];
        //$ymd                = date('Ymd',$nowTime);
        //$sn                 = 'CKD'.$userId.$ymd;var_dump($sn);exit;
        $sn                 = \App\Eloquent\Ygt\WarehouseOut::getSn();;
        $data               = [
            'user_id'=>$userId,
            'company_id'=>$companyId,
            'sn'=>$sn,
        ];
        $outId              = WarehouseOut::insertOneData($data,'id');
        if(!$outId)
        {
            xThrow(ERR_UNKNOWN,'出库单生成失败');
        }
        //发货单中的应收单相关联表的id
        $billRelationIdArr      = $billArr = [];
        foreach($requestRelationArr as $key=>$val)
        {
            $valBillRelationId      = $val['bill_relation_id'];
            $billRelationIdArr[]    = $valBillRelationId;
        }
        //取应收单相关联的信息
        $where              = ['id'=>['in',$billRelationIdArr] ];
        $raltionColletion   = WarehouseBillRelation::getList($where);
        $raltionList        = $raltionColletion->toArray();

        //更新应收单相关联的信息
        foreach($raltionList as $key=>$val)
        {
            $valBillRelationId  = $val['id'];
            $relationNumber     = 0;
            $preNumber          = $val['pre_number'];
            $warehouseId        = $val['warehouse_id'];
            foreach($requestRelationArr as $k=>$v)
            {
                if($valBillRelationId == $v['bill_relation_id'] )
                {
                    //更新应收单中的相关数据的实际发货数量
                    $relationNumber     = $v['number'];
                    $relationPackage    = isset($v['packages']) ? intval($v['packages']) : 0;
                    $tempData           = [
                        'number'=>$relationNumber,
                        'money'=>$v['number']*$v['price'],
                        'packages'=>$relationPackage,
                    ];
                    $where              = ['id'=>$valBillRelationId];
                    WarehouseBillRelation::updateOneData($where,$tempData);
                    //更新对应成品的信息
                    $where              = ['id'=>$warehouseId];
                    $warehouse          = Warehouse::getInfo($where);
                    $warehouseNumber    = $preNumber - $relationNumber;
                    if($warehouse)
                    {
                        $warehouseNowNumber = $warehouse->now_number;
                        //如果数量发生了变化,则更新数量,
                        if($warehouseNumber != 0){
                            $warehouseNowNumber = $warehouseNowNumber + $warehouseNumber;
                            $tempData           = ['now_number'=>$warehouseNowNumber];
                            Warehouse::updateOneData($where,$tempData);
                        }
                        //成品流水日志记录
                        $orderId                = $warehouse->order_id;
                        $customerId             = $warehouse->customer_id;
                        $sn                     = \App\Eloquent\Ygt\WarehouseLog::getSn($userId);
                        $logData                = [
                            'company_id'=>$companyId,
                            'user_id'=>$userId,
                            'warehouse_id'=>$warehouseId,
                            'sn'=>$sn,
                            'type'=>2,
                            'order_id'=>$orderId,
                            'customer_id'=>$customerId,
                            'all_number'=>$warehouseNowNumber,
                            'now_number'=>$relationNumber,
                        ];
                        \App\Eloquent\Ygt\WarehouseLog::insertOneData($logData,'id');
                    }
                }
            }
            $relationMoney              = $relationNumber*$val['price'];
            $raltionList[$key]['number']    = $relationNumber;
            $raltionList[$key]['packages']    = $relationPackage;
            $raltionList[$key]['money']     = $relationMoney;
        }
        //更新应收单的信息,数量,已处理等
        $raltionListGroup       = collect($raltionList)->groupBy('warehouse_bill_id')->toArray();
        foreach($raltionListGroup as $key=>$valData)
        {
            $money              = 0;
            foreach($valData as $k=>$v)
            {
                $money          += $v['price']*$v['number'];
            }
            $where              = ['id'=>$key];
//            $tempData           = ['deal_status'=>1,'money'=>$money,'now_money'=>$money];
//            $tempData           = ['deal_status'=>1,'now_money'=>$money];
            $tempData           = ['deal_status'=>1,'pre_money'=>$money,'now_money'=>$money];

            //修改交货单状态为已出库
            $tempData['status'] = 2;//已出库

            WarehouseBill::updateOneData($where,$tempData);
        }
        //其它信息
        $orderIdArr         = $raltionColletion->pluck('order_id');
        $orderColletion     = Order::whereIn('id',$orderIdArr)->get();
        $buyersAddressIdArr = $orderColletion->pluck('field_name_22')->all();
        $buyersIdArr        = $orderColletion->pluck('field_name_23','id')->all();
        $where              = ['id'=>['in',$buyersAddressIdArr]];
        $buyersAddressList  = BuyersAddress::getList($where)->toArray();
        $dataAll            = [];
        $arr            = [
            'created_at'=> $nowTime,
            'updated_at'=> $nowTime,
            'company_id'=> $companyId,
            'user_id'=> $userId,
            'warehouse_out_id'=> $outId,
        ];
        foreach($raltionList as $key=>$val)
        {
            $valOrderId                     = $val['order_id'];
            $arr['warehouse_bill_id']     = $val['warehouse_bill_id'];
            $arr['bill_relation_id']     = $val['id'];
            $arr['warehouse_id']     = $val['warehouse_id'];
            $arr['customer_id']     = $val['customer_id'];
            $arr['order_id']     = $val['order_id'];
            $arr['number']     = $val['number'];
            $arr['packages']     = $val['packages'];
            $arr['price']     = $val['price'];
            $arr['money']     = $val['price'] * $val['number'];
            $arr['buyers_name']     = \App\Engine\Customer::getNameById($val['customer_id']);;
            $provinceId     = $cityId = $areaId = 0;
            $provinceName   = $cityName = $areaName = $address = '';
            $buyersId       = 0;
            if(isset($buyersIdArr[$valOrderId]))
            {
                $buyersId   = $buyersIdArr[$valOrderId];
            }
            foreach($buyersAddressList as $k=>$v)
            {
                if($buyersId!=0 && $v['buyers_id'])
                {
                    $provinceId = $v['province_id'];
                    $cityId = $v['city_id'];
                    $areaId = $v['area_id'];
                    $provinceName = $v['province_name'];
                    $cityName = $v['city_name'];
                    $areaName = $v['area_name'];
                    $address = $v['address'];
                }
            }
            $arr['province_id']     = $provinceId;
            $arr['city_id']         = $cityId;
            $arr['area_id']         = $areaId;
            $arr['province_name']   = $provinceName;
            $arr['city_name']       = $cityName;
            $arr['area_name']       = $areaName;
            $arr['address']         = $address;
            $dataAll[]              = $arr;
        }
        \DB::table('ygt_warehouse_out_relation')->insert($dataAll);

        //生成出库单时,仓库给发货员发消息
        $customerOrderIdArr         = [];
        foreach($orderColletion as $key=>$val)
        {
            $customerOrderId    = $val->customer_order_id;
            if (!in_array($customerOrderId, $customerOrderIdArr)) {
                $customerOrderIdArr[] = $customerOrderId;
            }
        }
        if(!empty($customerOrderIdArr))
        {
            foreach($customerOrderIdArr as $key=>$val)
            {
                $arr                = [
                    'user_id'=>$userId,
                    'company_id'=>$companyId,
                    'foreign_key'=>$val,
                    'type_id'=>$outId,
                    'content'=>'有一个新的出库单需要发货',
                ];
                $this->sendMessageByType($arr);

                //给财务发送消息
                $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
                foreach ($privilegeIdList as $privilegeId) {
                    if ($privilegeId) {
                        $messageData        = [
                            'company_id' => $companyId,
                            'privilege_id' => $privilegeId,
                            'form_user_id' => $userId,
                            'to_user_id' => '',
                            'foreign_key' => $val,
                            'type' => 35,//无消息详情
                            'type_id' => $val,
                            'title' => '有新的出库单',
                            'content' =>  '有新的出库单',
                            'theme'=> '有新的出库单',
                        ];
                        \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);
                    }
                }

            }
        }
        return ['message'=>'成功'];
    }
    //发消息,默认生成出库单时,仓库给发货员发消息
    public static function sendMessageByType($arr,$type=0)
    {
        switch($type)
        {
            case 1:
                break;
            default:
                //生成出库单时,仓库给发货员发消息
//                $arr                = [
//                    'user_id'=>'当前登录人的id',
//                    'company_id'=>'当前登录人的厂id',
//                    'foreign_key'=>'分组外键id',
//                    'type_id'=>'type_id',
//                    'content'=>'消息的内容',
//                ];
                $messageType        = 37;
                $userId             = $arr['user_id'];
                $companyId          = $arr['company_id'];
                $foreignKey         = $arr['foreign_key'];
                $typeId             = $arr['type_id'];
                $messageContent     = $arr['content'];
                $title              = '生成出库单';
                //取厂下的所有仓库员
                $appnodeId          = 12;//发货员角色
                $userList           = \App\Eloquent\Ygt\Privilege::getPrivilegeUser( $companyId, $appnodeId );
                $toUserIdArr        = [];
                foreach($userList as $key=>$val)
                {
                    $toUserIdArr[]  = $val['user_id'];
                }
                $toUserIdStr        = implode(',',$toUserIdArr);
                $messageData        = [
                    'company_id' => $companyId,
                    'privilege_id' => 0,
                    'form_user_id' => $userId,
                    'to_user_id' => $toUserIdStr,
                    'foreign_key' => $foreignKey,
                    'type' => $messageType,
                    'type_id' => $typeId,
                    'title' => $title,
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);
            ///////////////////////////////////////
        }
    }
    //出库单列表,准备生成发货单
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
//        $page               = request('page',1);
//        $limit              = request('page_num',10);
//        $offset             = ($page-1)*$limit;
        $dealStatus         = request('deal_status',0);
        $keyword        = request('keyword','');

        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId];
        $where['deal_status']   = $dealStatus;
//        $outColltion        = WarehouseOut::getList($where,'',$limit,$offset);
        $outColltion        = WarehouseOut::getList($where);
        $outList            = $outColltion->toArray();

        $outIdArr           = $outColltion->pluck('id')->all();
        $where              = ['warehouse_out_id'=>['in',$outIdArr]];

        if(!empty($keyword)){
            $warehouseIdArr = Warehouse::where('product_name','like',"%".$keyword."%")->get()->pluck('id');
            $where['warehouse_id'] = ['in',$warehouseIdArr];
        }

        $relationColltion   = WarehouseOutRelation::getList($where);
        $relationList       = $relationColltion->toArray();
        $warehouseIdArr     = $relationColltion->pluck('warehouse_id')->all();
        $where              = ['id'=>['in',$warehouseIdArr]];
        $orderList          = Warehouse::getList($where)->toArray();
        $outListArr         = WarehouseOut::getRealtionData($outList,$relationList,$orderList);



        //转成发货单
        $customerId         = request('customer_id',0);
        foreach ($outListArr as $key => $value){
            if(!isset($value['warehouse_send_id'])){
                $value['warehouse_send_id'] = 0;
            }
            $tmpWarehousSendId = $value['warehouse_send_id'];
            $tmpWarehouseSendRow = \App\Eloquent\Ygt\WarehouseSend::where(['id'=>$tmpWarehousSendId])->first();
            if($tmpWarehouseSendRow){
                $outListArr[$key]['sn'] = $tmpWarehouseSendRow->sn;
                if($tmpWarehouseSendRow['status']){
                    $tmpStatusList  = config('status.warehouse_send_status');
                    if(isset($tmpStatusList[$tmpWarehouseSendRow['status']])){
                        $outListArr[$key]['sn'].= "【{$tmpStatusList[$tmpWarehouseSendRow['status']]['txt']}】";
                    }
                }
            }

            if($customerId){
                //过滤非客户的发货单
                $tmpWarehouseSendRelationList = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$tmpWarehousSendId])->get();
                foreach ($tmpWarehouseSendRelationList as $tmpWarehouseSendRelationRow){
                    if($tmpWarehouseSendRelationRow['customer_id'] != $customerId){
                        unset($outListArr[$key]);
                    }
                }
            }
        }

        $outListArr = array_values($outListArr);
        if($dealStatus == 1){//按发货单ID倒叙
            $tempData = [];
            //生成排序数组
            $tempArr = array_column($outListArr,'warehouse_send_id');
            $tempArr = array_flip($tempArr);
            krsort($tempArr);
            foreach($tempArr as $val){
                $tempData[] = $outListArr[$val];
            }
            $outListArr = $tempData;
        }
        return $outListArr;
    }


    ///////////////
    private function changeBillRelationColletion($colletion,$dealStatus=0,$type=0)
    {
        $warehouseIdArr     = $colletion->pluck('warehouse_id');
        $lists              = $colletion->toArray();
        $where              = ['id'=>['in',$warehouseIdArr]];
        $orderList          = Warehouse::getList($where)->toArray();
        $orderListArr       = [];
        foreach($orderList as $key=>$val)
        {
            $orderListArr[$val['order_id']] = $val;
        }
        $relationList       = [];
        foreach($lists as $key=>$val)
        {
            $orderId        = $val['order_id'];
            if(isset($orderListArr[$orderId]))
            {
                $order              = $orderListArr[$orderId];
                $temp               = $order;
                $temp['bill_relation_id']   = $val['id'];
                $temp['bill_id']        = $val['warehouse_bill_id'];
                if($dealStatus==1 && $type==1){
                    $temp['bill_number']    = $val['number'];

                    //如果number没有值取pre_number的值
                    if(!$val['number']){
                        $temp['bill_number']    = $val['pre_number'];
                    }

                }else{
                    $temp['bill_number']    = $val['pre_number'];
                }
                $temp['bill_money']    = $val['money'];
                $temp['price']          = $val['price'];
                $temp['packages']          = $val['packages'];
                $relationList[]      = $temp;
            }
        }
        $lists          = collect($relationList)->groupBy('bill_id')->toArray();
        return $lists;
    }
    private function changeOutColletion($colletion)
    {

    }
}